import React, { PureComponent } from "react";
import Header from "../../components/Header/Header";
import { $pre } from "../../http/http";
import "./Shop.less";
import yImg from "../../assets/img/y.jpeg";
import nImg from "../../assets/img/n.jpeg";
import { Button, SwipeAction, Dialog } from "antd-mobile";
import { filterPrice } from "../../filters";
import { bindActionCreators } from "redux";
import { actions, getAll, getAllPrice, getArr } from "../../store/modules/shop";
import { connect } from "react-redux";

class Shop extends PureComponent {
  componentDidMount() {
    let {shop:{reqList}} = this.props
    reqList()
  }
  
  render() {
    let {arr,allChecked,allPrice,shop:{add,sub,del,changeOne,changeAll}} = this.props

    return (
      <div>
        <Header title="购物车" back></Header>
        {arr.map((item, index) => (
          <SwipeAction
            key={item.id}
            closeOnAction={false}
            closeOnTouchOutside={false}
            rightActions={[
              {
                key: "delete",
                text: "删除",
                color: "danger",
                onClick: async () => {
                  await Dialog.confirm({
                    content: "确定要删除吗？",
                    onConfirm: () => {
                      del(item.id);
                    },
                  });
                },
              },
            ]}
          >
            <div className="item">
              <img
                className="checkbox"
                src={item.checked ? yImg : nImg}
                alt=""
              />
              <img
                onClick={() => changeOne(index)}
                className="img"
                src={$pre + item.img}
                alt=""
              />
              <div className="right">
                <h3>{item.goodsname}</h3>
                <div>￥{filterPrice(item.price)}</div>
                <div>
                  <Button onClick={() => sub(item.id, item.num)}>-</Button>
                  {item.num}
                  <Button onClick={() => add(item.id)}>+</Button>
                </div>
              </div>
            </div>
          </SwipeAction>
        ))}

        {/* 全选总价 */}
        <div className="footer">
          <div className="allChecked" onClick={() => changeAll()}>
            <img className="checkbox" src={allChecked ? yImg : nImg} alt="" />
            全选
          </div>
          <div className="allPrice"><span>总计:</span>￥{filterPrice(allPrice)}</div>
          <Button shape='default' color="warning" onClick={()=>this.props.history.push("/order")}>结算</Button>
        </div>
      </div>
    )
  }
}

const mapStateToProps = state =>{
  return {
    arr:getArr(state),
    allChecked:getAll(state),
    allPrice:getAllPrice(state)
  }
}
const mapDispatchToProps = dispatch =>{
  return {
    shop:bindActionCreators(actions,dispatch)
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(Shop)